<!--
角色管理页
单仕瑞
2017年4月12日 13:44:41
-->
<template>
  <div>
    <div v-if="isshow" >
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;height:46px">
        <el-form :inline="true" >
          <!--<el-form-item>-->
            <!--<el-input v-model="filters.deptName" size="small" placeholder="部门名称" style="margin-top:4px"></el-input>-->
          <!--</el-form-item>-->
          <!--<el-form-item>-->
            <!--<el-button type="primary" v-on:click="search" size="small" style="line-height:14px">查询</el-button>-->
          <!--</el-form-item>-->
          <el-form-item class="button-align">
            <el-button type="primary" @click="handleAdd" size="small">新增团队</el-button>
          </el-form-item>
          <el-form-item class="button-align">
            <el-button type="danger" @click="batchDelete" :disabled="this.sels.length===0" v-if="getAuth(3)" size="small">批量删除</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <!--列表-->
      <el-table :data="list"  @selection-change="selsChange" border style="width: 100%; font-size: 12px;" row-class-name="tabRow" v-loading="listLoading" tooltipEffect="light">
        <el-table-column type="selection" v-if="getAuth(3)"></el-table-column>
        <el-table-column align="center" prop="name" label="团队名称"></el-table-column>
        <el-table-column align="center" prop="deptname" label="所属部门"></el-table-column>
        <el-table-column align="center" label="操作">
          <template scope="scope">
            <el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)" v-if="getAuth(4)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)" v-if="getAuth(2)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="24" class="toolbar" v-show="!listLoading" style="margin-top: 15px;">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 30]" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;" id="pagination">
        </el-pagination>
      </el-col>

      <!--新增/修改-->
      <el-dialog :title="dialogTitle" :visible.sync="showAdd" :close-on-click-modal="false" width="600px" @close="clearValidate" style="top:10%">
        <el-form :model="deptEntity" label-width="150px" :rules="deptFormRules" ref="dept" style="margin-top:-20px">
          <el-form-item label="所属部门" prop="deptid">
            <el-select v-model="deptEntity.deptid" style="width: 100%" :disabled="true">
              <el-option v-for="(item, index) in deptList" :key="index" :label="item.deptName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="团队名称" prop="name">
            <el-input v-model="deptEntity.name" :disabled="this.checkDeptName" size="small" :maxlength="255"></el-input>
          </el-form-item>
          <el-form-item label="故障推送手机号" prop="name">
            <el-button type="primary" @click.native="addPhone" size="small">添加</el-button>
            <div v-for="(it,index) in deptEntity.phonesList" :key="index">
              <el-input style="width: calc(100% - 65px)" v-model="it.phone" :disabled="this.checkDeptName" size="small" :maxlength="255"></el-input>
              <el-button type="danger" @click.native="deptEntity.phonesList.splice(index,1)" size="small">删除</el-button>
            </div>
          </el-form-item>
        </el-form>

        <div scope="footer" class="dialog-footer"
             style="text-align: right;">
          <el-button @click.native="showAdd = false">取消</el-button>
          <el-button type="primary" @click.native="handleSubmit" :loading="saveDeptLoading">保存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  // import menuControl from './menuControl.vue'
  import {buttonAuth, resetBreads, sessionOut} from '../../smartlight/common/js/util.js'
  export default {
    data () {
      return {
        saveDeptLoading: false, // 保存部门动画按钮
        filters: {
          deptName: ''
        },
        isshow: true,
        deptList: [],
        total: 2,
        page: 1,
        pageSize: 10,
        checkDeptName: false, // 设置修改角色时【角色名称】灰化
        sels: [], // 列表选中列
        listLoading: false,
        showAdd: false,
        addLoading: false,
        companyId: '', // 公司id
        companytype: '', // 公司帐号类型
        tipsTitle: '提示',
        diaAlert: false, // 控制展示登录超时
        deptEntity: {
          id: '',
          name: '',
          lngLat: '',
          deptid: '',
          phonesList:[],
        },
        opType: 'add',
        type: '',
        dialogTitle: '新增团队',
        deptFormRules: {
          deptName: [
            {required: true, message: '请输入部门名称', trigger: 'blur'},
            {max: 255, message: '最多输入255个字符', trigger: 'blur'}
          ]
        },
        authButtons: [], // 组件权限按钮ID集合
        adminButtons: [346, 349, 348, 408, 347], // 依次为新增、权限控制、删除、批量删除、编辑
        ebookingButtons: [589, 590, 591, 592, 593], // 依次为新增、权限控制、删除、批量删除、编辑
        mdButtons: [354, 357, 356, 464, 355], // 依次为新增、权限控制、删除、批量删除、编辑
        list: [],
        user: JSON.parse(sessionStorage.getItem('user'))
      }
    },
    methods: {
      addPhone(){
        console.log(this.deptEntity.phonesList)
        if(this.deptEntity.phonesList.length < 5){
          this.deptEntity.phonesList.push({})
        }else {
          this.$message.error("最多添加5个手机号！")
        }
      },
      checkIfLogin () { // 判断是否登录超时
        var user = sessionStorage.getItem('user')
        if (!user) {
          this.$alert('登录超时，请重新登录！', ' ', {
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/login'})
            sessionStorage.clear()
          })
        } else {
          return true
        }
      },

      aginLogin () { // 登录超时后点击【确定】按钮事件--单仕瑞--2017年4月25日 16:36:53
        this.diaAlert = false
        this.$router.push({path: '/login'})
        sessionStorage.clear()
      },
      clearValidate () {
        this.$refs['dept'].resetFields()
      },

      handleSizeChange (val) { // 改变页面展示条数时触发重新查询--单仕瑞--2017年4月12日 13:44:41
        this.pageSize = val
        this.getList()
      },
      handleCurrentChange (val) { // 改变页面展示条数时触发重新查询--单仕瑞--2017年4月12日 13:44:41
        this.page = val
        this.getList()
      },
      search () { // 根据【角色名称】查询--单仕瑞--2017年4月20日 15:31:56
        if (!this.checkIfLogin()) {
          return
        }
        this.getList()
      },
      selsChange: function (sels) { // 设置选中列----单仕瑞--2017年4月12日 13:44:41
        this.sels = sels
      },
      handleAdd () { // 控制新增角色时的弹出层--单仕瑞--2017年4月12日 13:44:41
        this.checkDeptName = false
        this.showAdd = true
        this.opType = 'add'
        this.dialogTitle = '新增团队'
        this.deptEntity = {
          id: '',
          deptid: 4,
          name: '',
          phonesList:[],
        }
      },
      handleSubmit () { // 新增部门or修改部门时的提交
        if (!this.checkIfLogin()) {
          return
        }
        this.$refs.dept.validate((valid) => {
          if (valid) {
            var dept = {}
            var url = '/smartLight/web/sysTream/save.htm'
            console.log(this.deptEntity.phonesList)
            let phones = this.deptEntity.phonesList.map(it=>it.phone).filter(it=>it).join(",");
            dept.phones = phones;
            // 由于添加和更新的传参方式不同，此处分开处理
            if (this.opType === 'edit') {
              dept.id = this.deptEntity.id
              dept.name = this.deptEntity.name.trim()
              dept.deptid = this.deptEntity.deptid
              dept.type = this.companytype
            } else {
              dept.name = this.deptEntity.name.trim()
              dept.deptid = this.deptEntity.deptid
              dept.type = this.companytype
            }
            this.addLoading = true
            this.saveDeptLoading = true
            this.doUpdate(url, dept)
          }
        })
      },
      initDeptList () { // 初始化查询角色列表信息--单仕瑞--2017年4月12日 13:44:41
        this.listLoading = true

        var para = {
          pageNumber: 1,
          pageSize: 100,
          companyType: this.companytype,
          type: this.companytype,
          companyId: this.companyId
        }

        this.$http.post('/smartLight/web/sysDept/getList.htm', para).then(response => {
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.deptList = resBody.result.content
            this.listLoading = false
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      getList () { // 初始化查询角色列表信息--单仕瑞--2017年4月12日 13:44:41
        this.listLoading = true
        var user = JSON.parse(sessionStorage.getItem('user'))
        var para = {
          pageNumber: this.page,
          pageSize: this.pageSize,
          // type: this.companytype,
          // deptid: user.deptId
        }
        console.log(para)
        this.$http.post('/smartLight/web/sysTream/getList.htm', para).then(response => {
          var resBody = response.body
          console.log(resBody)
          if (resBody.isSuccess === 0) {
            this.list = resBody.result.content
            console.log(this.list)
            this.total = resBody.result.totalElements
            this.listLoading = false
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      doUpdate (url, params) { // 对后台操作后的结果在页面展示（成功or失败
        console.log(params)
        this.$http.post(url, params).then(response => {
          this.saveDeptLoading = false
          var resBody = response.body
//          console.log(resBody)
          if (resBody.isSuccess === 0) {
            this.showAdd = false
            this.addLoading = false
            this.$message({
              showClose: true,
              message: '操作成功',
              type: 'success'
            })
            this.getList()
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      handleEdit (index, row) { // 控制修改角色时的弹出层--单仕瑞--2017年4月12日 13:44:41
        this.checkDeptName = false
        this.showAdd = true
        this.opType = 'edit'
        this.dialogTitle = '编辑部门'
        this.deptEntity = Object.assign({}, row,{phonesList:row.phones?row.phones.split(",").map(it=>({phone:it})):[]})
      },
      handleDelete (index, row) { // 需要删除的id--单仕瑞--2017年4月12日 13:44:41
        var ids = []
        ids.push(row.id)
        this.deleteDept(ids)
      },
      batchDelete () { // 批量删除的id集合--单仕瑞--2017年4月12日 13:44:41
        var ids = []
        this.sels.map(item => {
          ids.push(item.id)
        })
        this.deleteDept(ids)
      },
      deleteDept (ids) { // 进行删除的方法--单仕瑞--2017年4月12日 13:44:41
        console.log(ids)
        if (!this.checkIfLogin()) {
          return
        }
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/smartLight/web/sysTream/delById.htm', ids + '|' + this.companytype).then(response => {
            var resBody = response.body
            if (resBody.isSuccess === 0 && resBody.errorMsg === '') {
              this.$message({
                showClose: true,
                message: '操作成功',
                type: 'success'
              })
              this.getList()
            } else if (resBody.isSuccess === 2) {
              this.listLoading = false
              sessionOut(this) // session超时处理
            } else {
              this.$message({
                showClose: true,
                message: '操作失败，' + resBody.errorMsg,
                type: 'error'
              })
              this.getList()
            }
          })
        }).catch(() => {})
      },
      // 获取页面按钮权限
      getAuth (index) {
        return buttonAuth(index, this.companytype, this.adminButtons, this.ebookingButtons, this.mdButtons)
      },
      // 面包屑处理 flag=0 权限控制进入;flag=1 权限控制提交
      updateBreads (flag) {
        var breads = this.$store.state.breads
        if (flag === 0) {
          if (breads.indexOf('权限控制') === -1) { // 不包含
            breads.push('权限控制')
          } else {
            breads.splice(breads.length - 1, 1)
          }
          this.$store.dispatch('updateBreads', breads)
        } else if (flag === 1) {
          if (breads.indexOf('权限控制') !== -1) {
            breads.splice(breads.length - 1, 1)
            this.$store.dispatch('updateBreads', breads)
          }
        }
      }
    },
    mounted () { // 钩子函数，相当于进入页面后的初始化
      var user = sessionStorage.getItem('user')
      if (user) {
        user = JSON.parse(user)
        this.companytype = user.type
        this.companyId = user.companyId
        this.deptEntity.deptName = this.deptName
        // 浏览器向前或向后处理
        resetBreads(this)
      }
      this.initDeptList()
      this.getList()
    },
    components: {
      // menuControl
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  .is-light
    max-width: 600px;
  .tabRow
    font-size: 12px;
  .button-align
    float: right;
  .el-dialog--small
    width: 37% ;
  .prompt
    color: #ff4949
    line-height: 10px !important;
    display: block;

  #formheight
    margin-left: -15px;
    margin-right: 10px;
    height: 38px;
    .el-form-item__content
      height: 30px;
    .el-input
      height: 30px;
      .el-input__inner
        height: 30px;

  .borderStyle
    .el-input .el-input__inner {
      border-color: #ff4949 !important;
    }

  #pagination
    background-color: transparent
    .el-input__inner
      width: 120px
</style>
